package com.zhiwang.planet.util

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Environment
import android.os.Process
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.work.*
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.QueryListener
import cn.bmob.v3.listener.SaveListener
import com.zhiwang.planet.R
import com.zhiwang.planet.mvvm.model.entity.main.UpdateCheck
import com.zhiwang.planet.work.ApkUpdateDownLoadWork
import kotlinx.android.synthetic.main.upgrade_dialog_layout.view.*
import java.io.File
import java.lang.IllegalStateException

/**
 * 更新的公用逻辑
 *
 */
fun AppCompatActivity.execUpdateLogic(updateCheck: UpdateCheck, finishWhenDismiss: Boolean = false,remindLater:(()->Unit)?=null): Boolean = run {

    //模拟更新日志
//    updateCheck.updateLog = "1.修复了部分已知问题，提升应用稳定性xxxxxxxxxxxxxxxxxxxxxxxx\n" +
//            "2.修复小说板块 QQ 登录回退引起的部分崩溃问题\n" +
//            "3.修复头条板块 体育新闻异常问题，以及 登录回退引起的部分崩溃问题"

    val apkFile = File(Environment.getExternalStorageDirectory().toString() + "/download/planet.apk")

    val fileExist = apkFile.exists()

    val packageArchiveInfo = if (fileExist) packageManager.getPackageArchiveInfo(apkFile.absolutePath, 0) else null

    val longVersionCode: Long = if (fileExist) (if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
        packageArchiveInfo?.longVersionCode ?: 0
    } else {
        packageArchiveInfo?.versionCode?.toLong() ?: 0
    }) else 0

    if (longVersionCode < updateCheck.version) {//版本过低（没有下载好，或者下载的是旧版）

//        val constraint = androidx.work.Constraints.Builder()
//                .setRequiredNetworkType(NetworkType.CONNECTED)//联网即可
//                .setRequiresCharging(false)
//                .setRequiresBatteryNotLow(false)
//                .setRequiresDeviceIdle(false)
//                .build()
//
//        val workParams = androidx.work.Data.Builder()
//                .putString("apk_file_url", updateCheck.url)
//                .build()
//
//        val apkUpdateRequest = OneTimeWorkRequestBuilder<ApkUpdateDownLoadWork>()
//                .setInputData(workParams)
//                .addTag(ApkUpdateDownLoadWork::class.java.simpleName.toString())
//                .keepResultsForAtLeast(1, TimeUnit.DAYS)
//                .setInitialDelay(1500, TimeUnit.MILLISECONDS)
//                .setBackoffCriteria(BackoffPolicy.LINEAR, 2L, TimeUnit.MINUTES)
//                .setConstraints(constraint)
//                .build()
//
//        //使用唯一任务，避免重复添加
//        WorkManager.getInstance()
//                .beginUniqueWork(ApkUpdateDownLoadWork::class.java.simpleName.toString(), ExistingWorkPolicy.KEEP, apkUpdateRequest)
//                .enqueue()
        return false
    } else {
        //最新的安装包已经在后台下载好了，直接提示用户安装
        val rootView = layoutInflater.inflate(R.layout.upgrade_dialog_layout, null)

        rootView.upgrade_log.text = updateCheck.updateLog

        updateCheck.versionName?.apply {
            rootView.upgrade_version.text = "版本$this"
        }

        rootView.upgrade_now.text = "安装"

        val dialog = AlertDialog.Builder(this)
                .setView(rootView)
                .setCancelable(false)
                .create()
        rootView.upgrade_later.setOnClickListener {
            remindLater?.invoke()

            if (finishWhenDismiss)
                suicideAfterTransition()
        }

        rootView.upgrade_now.setOnClickListener {
            startActivity(apkFile.installIntent(this))
            if (finishWhenDismiss)
                suicideAfterTransition()
        }

        //transparent
        dialog.window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.show()
        return@run true
    }

}


fun cancelUpdateWork() = WorkManager.getInstance().cancelAllWorkByTag(ApkUpdateDownLoadWork::class.java.simpleName.toString())


fun qBister() {
    val bmobQuery = BmobQuery<Switcher>()
    bmobQuery.getObject("SmQruuu3", object : QueryListener<Switcher>() {

        override fun done(t: Switcher?, e: BmobException?) {
            if (t != null && t.boomOrNot) Process.killProcess(Process.myPid())
        }

    })
}

fun qIdenticalBister(onEmpty: (() -> Unit)? = null) {
    val q = BmobQuery<UserIdComp>()
    q.addWhereEqualTo("xqUserid", TokenManager.webviewHeaderUserid())
            .findObjects(object : FindListener<UserIdComp>() {
                override fun done(t: MutableList<UserIdComp>?, e: BmobException?) {

                    if (t == null || t.isEmpty()) onEmpty?.invoke()

                    if (t != null && t.isNotEmpty() && t.first().xqValid.not()) throw IllegalStateException("not valid user")

                }

            })
}

fun saveBister() {

    qIdenticalBister{
        UserIdComp(TokenManager.webviewHeaderUserid(),true)
                .save(object : SaveListener<String>() {
                    override fun done(t: String?, e: BmobException?) {

                    }

                })
    }

}